package cn.csc.module.product.service.categorybrand;

import cn.csc.framework.common.pojo.PageResult;
import cn.csc.module.product.controller.admin.categorybrand.vo.CategoryBrandCreateReqVO;
import cn.csc.module.product.controller.admin.categorybrand.vo.CategoryBrandExportReqVO;
import cn.csc.module.product.controller.admin.categorybrand.vo.CategoryBrandPageReqVO;
import cn.csc.module.product.controller.admin.categorybrand.vo.CategoryBrandUpdateReqVO;
import cn.csc.module.product.convert.categorybrand.CategoryBrandConvert;
import cn.csc.module.product.dal.dataobject.categorybrand.CategoryBrandDO;
import cn.csc.module.product.dal.mysql.categorybrand.CategoryBrandMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.Collection;
import java.util.List;

import static cn.csc.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.csc.module.product.enums.ErrorCodeConstants.CATEGORY_BRAND_NOT_EXISTS;

/**
 * 品牌分类关联信息 Service 实现类
 *
 * @author liuchuang
 */
@Service
@Validated
public class CategoryBrandServiceImpl implements CategoryBrandService {

    @Resource
    private CategoryBrandMapper categoryBrandMapper;

    @Override
    public BigInteger createCategoryBrand(CategoryBrandCreateReqVO createReqVO) {
        // 插入
        CategoryBrandDO categoryBrand = CategoryBrandConvert.INSTANCE.convert(createReqVO);
        categoryBrandMapper.insert(categoryBrand);
        // 返回
        return categoryBrand.getId();
    }

    @Override
    public void updateCategoryBrand(CategoryBrandUpdateReqVO updateReqVO) {
        // 校验存在
        validateCategoryBrandExists(updateReqVO.getId());
        // 更新
        CategoryBrandDO updateObj = CategoryBrandConvert.INSTANCE.convert(updateReqVO);
        categoryBrandMapper.updateById(updateObj);
    }

    @Override
    public void deleteCategoryBrand(BigInteger id) {
        // 校验存在
        validateCategoryBrandExists(id);
        // 删除
        categoryBrandMapper.deleteById(id);
    }

    private void validateCategoryBrandExists(BigInteger id) {
        if (categoryBrandMapper.selectById(id) == null) {
            throw exception(CATEGORY_BRAND_NOT_EXISTS);
        }
    }

    @Override
    public CategoryBrandDO getCategoryBrand(BigInteger id) {
        return categoryBrandMapper.selectById(id);
    }

    @Override
    public List<CategoryBrandDO> getCategoryBrandList(Collection<BigInteger> ids) {
        return categoryBrandMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<CategoryBrandDO> getCategoryBrandPage(CategoryBrandPageReqVO pageReqVO) {
        return categoryBrandMapper.selectPage(pageReqVO);
    }

    @Override
    public List<CategoryBrandDO> getCategoryBrandList(CategoryBrandExportReqVO exportReqVO) {
        return categoryBrandMapper.selectList(exportReqVO);
    }

}
